package edu.hda.pt.client.connections.mina;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.mina.core.session.IoSession;

import edu.hda.pt.client.connections.PTClientMINA;

/**
 * Event handler for receiving synchronous messages
 * 
 * @author Marc Hammerton
 * 
 */
public class SyncClientProtocolHandler extends ClientProtocolHandler {

	private PTClientMINA client;

	/**
	 * Queue for taking values of synchronous messages
	 */
	final BlockingQueue<String> answer = new LinkedBlockingQueue<String>();

	/**
	 * Constructor setting the client objectt
	 * 
	 * @param client
	 *            - client object
	 */
	public SyncClientProtocolHandler(PTClientMINA client) {
		this.client = client;
	}

	/**
	 * This method is called whenever an exception is caught
	 * 
	 * @see org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(IoSession,
	 *      Throwable)
	 */
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) {
		session.close(true);
		System.out.println(client.clientID + " Exception:");
		System.out.println(cause);
	}

	/**
	 * This method is called when a message from the server is received. The
	 * message value is put into the queue.
	 * 
	 * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(IoSession,
	 *      Object)
	 */
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		answer.offer(message.toString());
	}

	/**
	 * @see edu.hda.pt.client.connections.mina.ClientProtocolHandler#responseReceived()
	 */
	public String responseReceived() {
		for (;;) {
			try {
				return answer.take();
			} catch (InterruptedException e) {
				// Ignore.
			}
		}
	}
}
